# encoding=gbk


def read_file(file_path):
    f = open(file_path, encoding='gbk')
    result_dict = {}

    for line in f.readlines():

        if line.split(':')[0] != 'epoch':
            continue

        for elements in line.split():
            element = elements.split(':')
            if element[0] == 'time':
                continue
            v = float(element[1])
            if element[0] not in result_dict:
                result_dict[element[0]] = [v]
            else:
                result_dict[element[0]].append(v)
    return result_dict


def find_best_mae(dic_result):
    epoch = dic_result['epoch']
    rmse = dic_result['rmse']
    mae = dic_result['mae']
    best_mae = min(mae)
    best_index = mae.index(best_mae)
    best_rmse = round(rmse[best_index], 4)
    best_epoch = epoch[best_index]
    best_mae = round(best_mae, 4)
    return best_epoch, best_rmse, best_mae


result_path = r'result/'
result_name = [
    'ARM_ML_1M_20480_rate_None.txt',
    'ARM_ML_1M_20480_rate_u.txt',
    'ARM_ML_1M_20480_rate_i.txt',
    'ARM_ML_1M_20480_rate_u_i.txt',

    'ARM_ML_100K_20480_rate_None.txt',
    'ARM_ML_100K_20480_rate_u.txt',
    'ARM_ML_100K_20480_rate_i.txt',
    'ARM_ML_100K_20480_rate_u_i.txt',

    'ARM_Musical_Instruments_20480_rate_None.txt',
    'ARM_Musical_Instruments_20480_rate_u.txt',
    'ARM_Musical_Instruments_20480_rate_i.txt',
    'ARM_Musical_Instruments_20480_rate_u_i.txt',

    'ARM_Amazon_fashion_20480_rate_None.txt',
    'ARM_Amazon_fashion_20480_rate_u.txt',
    'ARM_Amazon_fashion_20480_rate_i.txt',
    'ARM_Amazon_fashion_20480_rate_u_i.txt',

    'ARM_Epinions_20480_rate_None.txt',
    'ARM_Epinions_20480_rate_u.txt',
    'ARM_Epinions_20480_rate_i.txt',
    'ARM_Epinions_20480_rate_u_i.txt',

    'similarity_Epinions_20480_rate_None.txt',
    'Epinions_coe',
]
for name in result_name:
    path = result_path + name
    result_dic = read_file(path)
    epoch, rmse, mae = find_best_mae(result_dic)
    print(name)
    print('epoch:', epoch, '  rmse:', rmse, '  mae:', mae)
